/**
 * TODO(聊天界面js)
 * 1.文字 type 1 ， 声音 type 2 ， 图片 type 3
 * @date 2018/2/9 10:17
 **/
var util = require('../../utils/util.js');
var data;
var user_id;
var id;
var type;
var content = [];
var page = 1;
var requ = require("../../utils/emotion.js");
var emotion = requ.getjson();
var emo1 = [];
var emo2 = [];
var emo3 = [];
var emo4 = [];
var emo5 = [];
var that;

var recorderManager = wx.getRecorderManager()

// 播放音频
const innerAudioContext = wx.createInnerAudioContext()
innerAudioContext.autoplay = true

recorderManager.onStart(() => {

    console.log('recorder start')
})

/**
 * TODO(发送声音)
 * 1. 声音type = 2
 * @param
 * @date 2018/2/9 10:13
 **/
recorderManager.onStop((res) => {
    console.log(res);
    if (that.data.voice_time < 1000) {
        wx.showToast({
            title: '录音时间过短',
            icon: 'success',
            duration: 500
        })
        return;
    }
    var voice = {
        "url": res.tempFilePath,
        "length": parseInt(res.duration / 1000)
    }
    var msg = {
        content: voice,
        showLength: voice.length,
        showUrl: voice.url,
        loginName: that.data.login_name,
        headIco: that.data.head_ico,
        type: 2
    };
    content.push(msg);

    that.setData({
        content: content,
        functionshow: 0
    }, function () {
        that.scroll();
    })

    sendVoiceMsg(voice.url, voice.length, that);

})


var viop = {
    duration: 600000,
    sampleRate: 44100,
    numberOfChannels: 1,
    encodeBitRate: 192000,
    format: 'mp3',
    frameSize: 50
}


for (var i = 0; i < emotion.length; i++) {
    if (i < 21) {
        emo1.push(emotion[i]);
    } else if (i >= 21 && i < 42) {
        emo2.push(emotion[i]);
    } else if (i >= 42 && i < 63) {
        emo3.push(emotion[i]);
    } else if (i >= 63 && i < 84) {
        emo4.push(emotion[i]);
    } else if (i >= 84 && i < 105) {
        emo5.push(emotion[i]);
    }
}

function getChatInfo2 () {
    user_id = wx.getStorageSync('user_id');
    wx.request({
        url: getApp().globalData.javaurl + '/common/chat/getChatInfo',
        method: 'POST',
        data: {
            "id": id,
            "type": type,
            "page": page,
            "pageSize": 5
        },
        header: {
            "content-type": "application/x-www-form-urlencoded",
            "Authorization": wx.getStorageSync('token')
        },
        success: function (res) {
        }
    })
}

function getChatInfo (that) {
    that.setData({
        loading: 1
    })
    user_id = wx.getStorageSync('user_id');
    wx.request({
        url: getApp().globalData.javaurl + '/common/chat/getChatInfo',
        method: 'POST',
        data: {
            "id": id,
            "type": type,
            "page": page,
            "pageSize": 5
        },
        header: {
            "content-type": "application/x-www-form-urlencoded",
            "Authorization": wx.getStorageSync('token')
        },
        success: function (res) {
            //console.log(res.data);
            if (res.data.isSuccess == 1) {
                for (var i = 0; i < res.data.data.length; i++) {
                    if (+res.data.data[i].type === 2 || +res.data.data[i].type === 3) {
                        res.data.data[i].showLength = JSON.parse(res.data.data[i].content)['length']
                        res.data.data[i].showUrl = JSON.parse(res.data.data[i].content)['url']
                    }
                    content.unshift(res.data.data[i]);
                }
                if (page == 1) {
                    that.setData({
                        content: content,
                        loading: -1
                    }, function () {
                        that.scroll();
                    })
                } else {
                    that.setData({
                        content: content,
                        loading: -1
                    })
                }

                page++;
            } else {
                that.setData({
                    loading: 0
                })
            }


        }
    })
}


function sendTextMsg (msg, that) {
    wx.request({
        url: getApp().globalData.javaurl + '/common/chat/sendTextMsg',
        method: 'POST',
        data: {
            "toUserId": id,
            "content": msg
        },
        header: {
            "content-type": "application/x-www-form-urlencoded",
            "Authorization": wx.getStorageSync('token')
        }
    })
}

function sendLocationMsg (address, that) {
    wx.request({
        url: getApp().globalData.apiurl + 'sendLocationMsg',
        method: 'POST',
        data: {
            "chat_id": that.data.data.chat_id,
            "fm": that.data.data.me.id,
            "t": that.data.data.you.id,
            "content": address
        },
        header: {
            "content-type": "application/x-www-form-urlencoded"
        }
    })
}


function sendVoiceMsg (msg, length, that) {
    wx.uploadFile({
        url: getApp().globalData.javaurl + '/common/chat/sendVoiceMsg',
        filePath: msg,
        name: 'voice',
        formData: {
            "toUserId": id,
            "length": length
        },
        header: {
            "content-type": "application/x-www-form-urlencoded",
            "Authorization": wx.getStorageSync('token')
        },
        success: function (res) {
            console.log(res);
        }
    })
}

function sendImageMsg (msg, that) {
    wx.uploadFile({
        url: getApp().globalData.javaurl + '/common/chat/sendImageMsg',
        filePath: msg,
        name: 'img',
        formData: {
            "toUserId": id
        },
        header: {
            "content-type": "application/x-www-form-urlencoded",
            "Authorization": wx.getStorageSync('token')
        },
        success: function (res) {
            console.log(res);
        }
    })
}


Page({
    scroll: function () {
        var query = wx.createSelectorQuery()
        query.select('.body').boundingClientRect()
        query.selectViewport().scrollOffset()
        query.exec(function (res) {
            //console.log(res);
            setTimeout(function () {
                wx.pageScrollTo({
                    scrollTop: res[0].height
                });
            }, 200)
        })
        this.setData({
            new: 0
        })
    },
    /**
     * 页面的初始数据
     */
    data: {
        functionshow: 0,
        emojishow: 0,
        text_or_vioce: 0,
        inputVal: "",
        emo1: emo1,
        emo2: emo2,
        emo3: emo3,
        emo4: emo4,
        emo5: emo5,
        loading: -1,
        login_name: wx.getStorageSync('login_name'),
        head_ico: wx.getStorageSync('head_ico'),
        new: 0
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        id = options.id;
        type = options.type;
        that = this;

    },
    loadingMore: function () {
        var that = this;
        getChatInfo(that);
    },
    sendTextMsg: function (e) {
        var that = this;

        var value = e.detail.value;
        var msg = {
            content: that.data.inputVal,
            loginName: that.data.login_name,
            headIco: that.data.head_ico,
            type: 1
        };
        content.push(msg);
        that.setData({
            content: content,
            inputVal: ""
        }, function () {
            that.scroll();
        })
        sendTextMsg(msg.content, that);
    },
    bighidden: function () {
        this.setData({
            emojishow: 0,
            functionshow: 0,
            text_or_vioce: 0
        })
    },
    emojishow: function () {
        if (this.data.emojishow == 0) {
            this.setData({
                emojishow: 1,
                functionshow: 0,
                text_or_vioce: 0
            })
        } else {
            this.setData({
                emojishow: 0
            })
        }

    },
    functionshow: function () {
        if (this.data.functionshow == 0) {
            this.setData({
                emojishow: 0,
                functionshow: 1,
                text_or_vioce: 0
            })
        } else {
            this.setData({
                functionshow: 0
            })
        }
    },
    clickemoji: function (e) {
        console.log(this.data.inputVal + e.currentTarget.dataset.val);
        this.setData({
            inputVal: this.data.inputVal + e.currentTarget.dataset.val
        });
    },
    //按下事件开始
    mytouchstart: function (e) {
        recorderManager.start(viop);
    },
    //按下事件结束
    mytouchend: function (e) {
        recorderManager.stop();
    },
    changetovoice: function () {
        if (this.data.text_or_vioce == 1) {
            this.setData({
                text_or_vioce: 0,
                emojishow: 0,
                functionshow: 0
            })
        } else {
            this.setData({
                text_or_vioce: 1,
                emojishow: 0,
                functionshow: 0
            })
        }
    },
    inputTyping: function (e) {
        this.setData({
            inputVal: e.detail.value
        });
    },
    onReady: function () {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
        this.setData({
            login_name: wx.getStorageSync('login_name'),
            head_ico: wx.getStorageSync('head_ico')
        })
        content = [];
        page = 1;
        var that = this;
        getChatInfo(that);
        getApp().addListenerchat(function (data) {
            console.log(data);
            if (type == "friend") {
                console.log("friend");
                for (var i = 0; i < data.friend.length; i++) {
                    if (data.friend[i].loginName == id) {
                        if (+data.friend[i].type === 2 || +data.friend[i].type === 3) {
                            data.friend[i].showLength = JSON.parse(data.friend[i].content)['length']
                            data.friend[i].showUrl = JSON.parse(data.friend[i].content)['url']
                        }
                        var msg = {
                            content: data.friend[i].content,
                            loginName: data.friend[i].loginName,
                            showLength: data.friend[i].showLength,
                            showUrl: data.friend[i].showUrl,
                            headIco: data.friend[i].headIco,
                            type: data.friend[i].type
                        };
                        content.push(msg);
                        that.setData({
                            content: content,
                            new: 1
                        })
                        getChatInfo2();
                        wx.vibrateShort();
                    }
                }
            } else if (type == "group") {
                console.log("group");
                for (var i = 0; i < data.group.length; i++) {
                    if (data.group[i].groupId == id) {
                        if (+data.group[i].type === 2 || +data.group[i].type === 3) {
                            data.group[i].showLength = JSON.parse(data.group[i].content)['length']
                            data.group[i].showUrl = JSON.parse(data.group[i].content)['url']
                        }
                        var msg = {
                            content: data.group[i].content,
                            loginName: data.group[i].loginName,
                            showLength: data.friend[i].showLength,
                            showUrl: data.friend[i].showUrl,
                            headIco: data.group[i].headIco,
                            type: data.group[i].type
                        };
                        content.push(msg);
                        that.setData({
                            content: content,
                            new: 1
                        })
                        getChatInfo2();
                        wx.vibrateShort();
                    }
                }
            }
        });

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {
        this.setData({
            new: 0
        })
    },

    /**
     * 用户点击右上角分享
     */

    look_pic: function (e) {
        wx.previewImage({
            current: e.currentTarget.dataset.src, // 当前显示图片的http链接
            urls: [e.currentTarget.dataset.src] // 需要预览的图片http链接列表
        })
    },
    looklocation: function (e) {
        // var dataset = e.currentTarget.dataset;
        // wx.openLocation({
        //   latitude: dataset.latitude,
        //   longitude: dataset.longitude,
        //   scale:18,
        //   name:dataset.name,
        //   address:dataset.address
        // })
    },
    read: function (e) {
        var src = e.currentTarget.dataset.src;
        console.log(src);
        if (src.substring(0, 4) == "wxfi") {
            console.log("本地声音文件播放");
            // wx.playVoice({
            //     filePath: src
            // })
            innerAudioContext.src = src
            innerAudioContext.onPlay(() => {
                console.log('开始播放')
            })
            innerAudioContext.onError((res) => {
                console.log(res.errMsg)
                console.log(res.errCode)
            })
        } else if (src.substring(0, 4) == "http") {
            console.log("远程声音文件播放");
            wx.downloadFile({
                url: src, //仅为示例，并非真实的资源
                success: function (res) {
                    // wx.playVoice({
                    //     filePath: res.tempFilePath
                    // })
                    innerAudioContext.src = res.tempFilePath
                    innerAudioContext.onPlay(() => {
                        console.log('开始播放')
                    })
                    innerAudioContext.onError((res) => {
                        console.log(res.errMsg)
                        console.log(res.errCode)
                    })
                }
            })
        }
    },
    photo: function () {
        var that = this;
        wx.chooseImage({
            count: 1, // 默认9
            sizeType: ['compressed'], // 可以指定是原图还是压缩图，默认二者都有
            success: function (res) {

                var tempFilePaths = res.tempFilePaths[0];

                var img = {
                    "url": tempFilePaths
                }
                var msg = {
                    content: img,
                    loginName: that.data.login_name,
                    showUrl: img.url,
                    headIco: that.data.head_ico,
                    type: 3
                };
                content.push(msg);

                that.setData({
                    content: content,
                    functionshow: 0
                }, function () {
                    that.scroll();
                })
                sendImageMsg(img.url, that);


            }
        })
    },
    look_user: function (e) {
        return;
        // wx.redirectTo({
        //   url: "/pages/user/info?id="+e.target.dataset.id
        // })
    },
    location: function () {
        getApp().alert("该功能暂未开放");
        return;
        // var that = this;
        // wx.chooseLocation({
        //   success: function(res) {
        //     console.log(res);
        //     var name = res.name;
        //     var address = res.address;
        //     var latitude = res.latitude;
        //     var longitude = res.longitude;
        //     var address = {
        //       "name":name,
        //       "address":address,
        //       "latitude":latitude,
        //       "longitude":longitude
        //     }

        //     var msg = {
        //       content:address,
        //       from_me:1,
        //       type:5
        //     };
        //     content.push(msg);
        //     that.setData({
        //       content: content,
        //       functionshow: 0
        //     },function(){
        //       that.scroll();
        //     })

        //     sendLocationMsg(JSON.stringify(address),that);
        //   }
        // })
    }
})